package com.ysd.service.controller;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ysd.service.bean.ClockInteractionBean;
import com.ysd.service.config.MqttConfig;
import com.ysd.service.dto.ClockDto;
import com.ysd.service.entity.AlarmTimeEntity;
import com.ysd.service.entity.Clock;
import com.ysd.service.enums.ClockInteractionEnum;
import com.ysd.service.gateway.WeatherAPIClient;
import com.ysd.service.scheduled.ClockPushScheduled;
import com.ysd.service.service.ClockService;
import com.ysd.service.util.IBeanUtils;
import com.ysd.service.util.MqttMessageUtil;
import com.ysd.service.util.ObjUtil;
import com.ysd.service.util.Result;
import com.ysd.service.vo.ClockVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class ClockController {

    @Autowired
    private ClockService clockService;
    @Autowired
    private MqttConfig mqttConfig;
    @Autowired
    private MqttMessageUtil mqttMessageUtil;

    /**
     * 根据用户查询用户下的闹钟列表
     */
    @RequestMapping(value = "/clock/list", method = RequestMethod.POST)
    public Result<List<ClockVo>> listClockByUser(@RequestBody String openid){
        log.info("/clock/list.param = " + openid);
        List<Clock> clockList = clockService.queryClocksByUser(openid);
        List<ClockVo> voList = IBeanUtils.copyProperties(clockList, ClockVo.class);
        log.info("/clock/list.result = " + voList);
        return Result.buildResult(Result.Status.OK,"OK", voList);
    }

    /**
     * 查询闹钟详情
     */
    @RequestMapping(value = "/clock/detail", method = RequestMethod.POST)
    public Result<ClockVo> listClockDetail(@RequestBody String clockId){
        log.info("/clock/detail.param = " + clockId);
        Clock clock = clockService.queryClocksDetail(clockId);
        ClockVo vo = IBeanUtils.copyProperties(clock, ClockVo.class);
        vo.setSetAlarmTime(ObjUtil.convertStringToListMap(clock.getSetAlarmTime()));
        log.info("/clock/detail.result = " + vo);
        return Result.buildResult(Result.Status.OK,"OK", vo);
    }

    /**
     * 添加闹钟
     */
    @RequestMapping(value = "/clock/add", method = RequestMethod.POST)
    public Result addClock(@RequestBody ClockDto dto){
        log.info("/clock/add.param = " + dto);

        // 查询当前设备是否绑定过，表中存在则提示设备已绑定，不存在则添加设备
        List<Clock> clockList = clockService.queryClockByDeviceIdOpenid(dto.getDeviceId(), dto.getOpenId());
        if(clockList.size() > 0){
            return Result.buildResult(Result.Status.INTERNAL_SERVER_ERROR,"当前设备已绑定");
        }

        Clock entity = new Clock();
        entity.setOpenId(dto.getOpenId());
        entity.setClockName(dto.getClockName());
        entity.setBindSource(dto.getBindSource());// 绑定来源
        entity.setDeviceId(dto.getDeviceId());// 设备ID
        entity.setProvince("");// 省
        entity.setCity("");// 市
        entity.setLightSwitch(0);// 灯光开关（0关；1开）
        entity.setHourlyBroadcastSwitch(0);// 整点播报开关（0关；1开）
        entity.setColorSetting("00FF00");// 颜色设置
        entity.setBrightnessSetting(5);// 亮度设置（0-100）
        entity.setRelay1Switch(0);// 未知开关1（0关；1开）
        entity.setRelay2Switch(0);// 未知开关2（0关；1开）
        entity.setRelay3Switch(0);// 未知开关3（0关；1开）
        entity.setPowerSwitchLeft(1);// 电源左开关（0关；1开）
        entity.setPowerSwitchRight(1);// 电源右开关（0关；1开）
        entity.setOnLineState(0);// 在线状态（0离线；1在线）
        entity.setSetAlarmTime("[{time=09:00, enabled=false}, {time=14:00, enabled=false}, {time=18:00, enabled=false}]");// 设置闹钟时间
        entity.setCreateDate(new DateTime());// 创建时间
        entity.setCreateBy(dto.getOpenId());// 创建人
        entity.setRemarks("");// 备注
        entity.setDelFlag(0);// 是否删除（1删除）
        clockService.addClock(entity);

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 编辑闹钟操作
     */
    @RequestMapping(value = "/clock/edit", method = RequestMethod.PUT)
    public Result editClock(@RequestBody ClockDto dto){
        log.info("/clock/edit.param = " + dto);

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setClockName(dto.getClockName());
        entity.setLightSwitch(dto.getLightSwitch());// 灯光开关（0开；1关）
        entity.setHourlyBroadcastSwitch(dto.getHourlyBroadcastSwitch());// 整点播报开关（0开；1关）
        entity.setColorSetting(dto.getColorSetting());// 颜色设置
        entity.setBrightnessSetting(dto.getBrightnessSetting());// 亮度设置（0-100）
        entity.setSetAlarmTime(dto.getSetAlarmTime().toString());// 设置闹钟时间
        clockService.editClock(entity);

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 修改闹钟名称
     */
    @RequestMapping(value = "/clock/editClockName", method = RequestMethod.PUT)
    public Result editClockName(@RequestBody ClockDto dto){
        log.info("/clock/editClockName.param = " + dto);

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setClockName(dto.getClockName());
        clockService.editClock(entity);

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 绑定闹钟城市
     */
//    @RequestMapping(value = "/clock/storeClockAddress", method = RequestMethod.PUT)
//    public Result storeClockAddress(@RequestBody ClockDto dto){
//        log.info("/clock/storeClockAddress.param = " + dto);
//
//        Clock entity = new Clock();
//        entity.setId(dto.getId());
//        entity.setProvince(dto.getProvince());
//        entity.setCity(dto.getCity());
//        clockService.editClock(entity);
//
//        return Result.buildResult(Result.Status.OK,"OK");
//    }

    /**
     * 灯光开关（0关，1开）
     */
    @RequestMapping(value = "/clock/edit/lightSwitch", method = RequestMethod.PUT, produces = "application/json")
    public Result editClockLightSwitch(@RequestBody ClockDto dto){
        log.info("/clock/edit/lightSwitch.param = " + dto);
        log.info("请求灯光开关接口");

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setLightSwitch(dto.getLightSwitch());// 灯光开关（0开；1关）
        clockService.editClock(entity);

        // 发送灯光开关变化给设备端
        ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.LIGHT_SWITCH.getTypeCode());
        entity.setDeviceId(clockService.queryClocksDeviceId(dto.getId()));
        config.setData(JSONObject.toJSONString(entity));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 整点播报开关（0关；1开）
     */
    @RequestMapping(value = "/clock/edit/hourlyBroadcastSwitch", method = RequestMethod.PUT, produces = "application/json")
    public Result editClockHourlyBroadcastSwitch(@RequestBody ClockDto dto){
        log.info("/clock/edit/hourlyBroadcastSwitch.param = " + dto);

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setHourlyBroadcastSwitch(dto.getHourlyBroadcastSwitch());// 整点播报开关（0开；1关）
        clockService.editClock(entity);

        // 发送整点播报开关变化给设备端
        ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.HOURLY_BROADCAST_SWITCH.getTypeCode());
        entity.setDeviceId(clockService.queryClocksDeviceId(dto.getId()));
        config.setData(JSONObject.toJSONString(entity));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 颜色设置：参数16色
     */
    @RequestMapping(value = "/clock/edit/colorSetting", method = RequestMethod.PUT, produces = "application/json")
    public Result editClockColorSetting(@RequestBody ClockDto dto){
        log.info("/clock/edit/colorSetting.param = " + dto);

        // 去掉前面的#
        String color = dto.getColorSetting().replace("#", "");

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setColorSetting(color);// 颜色设置
//        clockService.editClock(entity);

        LambdaUpdateWrapper<Clock> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(Clock::getId, dto.getId());
        updateWrapper.set(Clock::getColorSetting, color);
        clockService.update(updateWrapper);

        // 发送颜色设置变化给设备端
        ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.COLOR_SETTING.getTypeCode());
        entity.setDeviceId(clockService.queryClocksDeviceId(dto.getId()));
        config.setData(JSONObject.toJSONString(entity));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 亮度设置（0-100）
     */
    @RequestMapping(value = "/clock/edit/brightnessSetting", method = RequestMethod.PUT, produces = "application/json")
    public Result editClockBrightnessSetting(@RequestBody ClockDto dto){
        log.info("/clock/edit/brightnessSetting.param = " + dto);

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setBrightnessSetting(dto.getBrightnessSetting());// 亮度设置（0-100）
//        clockService.editClock(entity);

        LambdaUpdateWrapper<Clock> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.eq(Clock::getId, dto.getId());
        updateWrapper.set(Clock::getBrightnessSetting, dto.getBrightnessSetting());
        clockService.update(updateWrapper);

        // 发送亮度设置变化给设备端
        ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.BRIGHTNESS_SETTING.getTypeCode());
        entity.setDeviceId(clockService.queryClocksDeviceId(dto.getId()));
        config.setData(JSONObject.toJSONString(entity));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 设置闹钟时间
     */
    @RequestMapping(value = "/clock/edit/setAlarmTime", method = RequestMethod.PUT, produces = "application/json")
    public Result editClockSetAlarmTime(@RequestBody ClockDto dto){
        log.info("/clock/edit/setAlarmTime.param = " + dto);

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setSetAlarmTime(dto.getSetAlarmTime().toString());// 设置闹钟时间
        clockService.editClock(entity);

        // 发送闹钟设置时间变化给设备端
        ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.SET_ALARM_TIME.getTypeCode());
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("id", dto.getId());
        paramMap.put("deviceId", clockService.queryClocksDeviceId(dto.getId()));
        List<Map<String, Object>> mapList = dto.getSetAlarmTime();
        AlarmTimeEntity alarmTimeEntity = new AlarmTimeEntity();
        alarmTimeEntity.setClockTime1(mapList.get(0).get("time").toString());
        alarmTimeEntity.setClockSwitch1(mapList.get(0).get("enabled").toString());
        alarmTimeEntity.setClockTime2(mapList.get(1).get("time").toString());
        alarmTimeEntity.setClockSwitch2(mapList.get(1).get("enabled").toString());
        alarmTimeEntity.setClockTime3(mapList.get(2).get("time").toString());
        alarmTimeEntity.setClockSwitch3(mapList.get(2).get("enabled").toString());
        paramMap.put("setAlarmTime", alarmTimeEntity);
        config.setData(JSONObject.toJSONString(paramMap));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 未知开关1（0关，1开）
     */
    @RequestMapping(value = "/clock/edit/relay1Switch", method = RequestMethod.PUT, produces = "application/json")
    public Result editClockRelay1Switch(@RequestBody ClockDto dto){
        log.info("/clock/edit/relay1Switch.param = " + dto);

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setRelay1Switch(dto.getRelay1Switch());
        clockService.editClock(entity);

        // 发送灯光开关变化给设备端
        ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.RELAY1_SWITCH.getTypeCode());
        entity.setDeviceId(clockService.queryClocksDeviceId(dto.getId()));
        config.setData(JSONObject.toJSONString(entity));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 未知开关2（0关，1开）
     */
    @RequestMapping(value = "/clock/edit/relay2Switch", method = RequestMethod.PUT, produces = "application/json")
    public Result editClockRelay2Switch(@RequestBody ClockDto dto){
        log.info("/clock/edit/relay2Switch.param = " + dto);

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setRelay2Switch(dto.getRelay2Switch());
        clockService.editClock(entity);

        // 发送灯光开关变化给设备端
        ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.RELAY2_SWITCH.getTypeCode());
        entity.setDeviceId(clockService.queryClocksDeviceId(dto.getId()));
        config.setData(JSONObject.toJSONString(entity));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 未知开关3（0关，1开）
     */
    @RequestMapping(value = "/clock/edit/relay3Switch", method = RequestMethod.PUT, produces = "application/json")
    public Result editClockRelay3Switch(@RequestBody ClockDto dto){
        log.info("/clock/edit/relay3Switch.param = " + dto);

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setRelay3Switch(dto.getRelay3Switch());// 灯光开关（0开；1关）
        clockService.editClock(entity);

        // 发送灯光开关变化给设备端
        ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.RELAY3_SWITCH.getTypeCode());
        entity.setDeviceId(clockService.queryClocksDeviceId(dto.getId()));
        config.setData(JSONObject.toJSONString(entity));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 电源左开关（0关，1开）
     */
    @RequestMapping(value = "/clock/edit/powerSwitchLeft", method = RequestMethod.PUT, produces = "application/json")
    public Result editClockPowerSwitchLeft(@RequestBody ClockDto dto){
        log.info("/clock/edit/powerSwitchRight.param = " + dto);

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setPowerSwitchLeft(dto.getPowerSwitchLeft());
        clockService.editClock(entity);

        // 发送灯光开关变化给设备端
        ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.POWER_SWITCH_LEFT.getTypeCode());
        entity.setDeviceId(clockService.queryClocksDeviceId(dto.getId()));
        config.setData(JSONObject.toJSONString(entity));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 电源右开关（0关，1开）
     */
    @RequestMapping(value = "/clock/edit/powerSwitchRight", method = RequestMethod.PUT, produces = "application/json")
    public Result editClockPowerSwitchRight(@RequestBody ClockDto dto){
        log.info("/clock/edit/powerSwitchRight.param = " + dto);

        Clock entity = new Clock();
        entity.setId(dto.getId());
        entity.setPowerSwitchRight(dto.getPowerSwitchRight());
        clockService.editClock(entity);

        // 发送灯光开关变化给设备端
        ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.POWER_SWITCH_RIGHT.getTypeCode());
        entity.setDeviceId(clockService.queryClocksDeviceId(dto.getId()));
        config.setData(JSONObject.toJSONString(entity));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());

        return Result.buildResult(Result.Status.OK,"OK");
    }

    /**
     * 删除闹钟
     */
    @RequestMapping(value = "/clock/delete", method = RequestMethod.DELETE)
    public Result deleteClock(@RequestBody String clockId){
        log.info("/clock/delete.param = " + clockId);

        // 删除该用户对应的设备闹钟
        clockService.delClockById(clockId);

        // 同步闹钟删除变化给设备端
        /*ClockInteractionBean config = new ClockInteractionBean();
        config.setType(ClockInteractionEnum.DELETE_CLOCK.getTypeCode());
        ClockDto entity = new ClockDto();
        entity.setId(clockId);
        entity.setDeviceId(clockService.queryClocksDeviceId(clockId));
        config.setData(JSONObject.toJSONString(entity));
        mqttMessageUtil.sendToMqtt(JSONObject.toJSONString(config), mqttConfig.getMqttDeviceTopic());*/

        return Result.buildResult(Result.Status.OK,"OK");
    }

    public static void main(String[] args) {
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("time", "09:00");
        map1.put("enabled", true);
        list.add(map1);
        Map<String, Object> map2 = new HashMap<>();
        map2.put("time", "12:00");
        map2.put("enabled", false);
        list.add(map2);
        System.out.println(list.toString());
        List<Map<String, Object>> list1 = ObjUtil.convertStringToListMap(list.toString());
        list1.forEach(e->{
            System.out.println(e.get("time"));
            System.out.println(e.get("enabled"));
        });
    }
}
